package com.newsee.remote.common.utils.webservice;

import com.newsee.remote.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * @author liangzhi.chen
 * @description xml
 * @date 2019/7/25 上午 11:37
 **/
@Slf4j
public class HttpWebserviceExecutor {

    public static String doHttpMethod(String url, String xml) {
        String list = StringUtils.EMPTY;
        try {
            URL urlNew = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlNew.openConnection();
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            log.info(xml);
            dos.write(xml.getBytes(StandardCharsets.UTF_8));
            dos.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder strBuf = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                strBuf.append(line);
            }
            dos.close();
            reader.close();
            String result = strBuf.toString();
            log.info(result);

            // 创建SAXReader阅读器对象
            SAXReader saxReader = new SAXReader();
            // 根据字符串构建字节数组输入流
            InputStream is = new ByteArrayInputStream(result.getBytes(CHARSET));
            // 命令阅读器从输入流中读取文档对象
            Document document = saxReader.read(is);
            // 获得文档对象的根节点
            Element root = document.getRootElement();
            // 获取根节点下面名叫user_info的节点
            Element body = root.element("Body");
            Element response = body.element("response");
            Element header = response.element("HEADER");
            //事务号
            String biztransactionid = header.element("BIZTRANSACTIONID").getText();
            String resultIdm = header.element("RESULT").getText();
            String errorcode = header.element("ERRORCODE").getText();
            String errorinfo = header.element("ERRORINFO").getText();
            String comments = header.element("COMMENTS").getText();
            String successcount = header.element("SUCCESSCOUNT").getText();
            if ("0".equals(resultIdm)) {
                list = response.element("LIST").getText();
                return list;
            } else {
                log.error("人员组织增量同步查询接口出错：" + url + "biztransactionid：" + biztransactionid + "；result：" + resultIdm + "；errorcode：" + errorcode
                        + "；errorinfo：" + errorinfo + "；comments：" + comments + "；successcount：" + successcount);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new ServiceException();
        }
        return list;
    }

    /**
     * 获取带有权限的HttpClient连接
     *
     * @param account  账号
     * @param password 密码
     * @return HttpClient链接
     */
    private static CloseableHttpClient getHttpClient(String account, String password) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(account, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        return HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    }

    /**
     * 请求接口
     *
     * @param url 请求的url
     * @param xml 请求体
     * @return response
     */
    public static String doPostSap(String url, String xml, String sapAccount, String sapPassword) {
        String response = "";
        try {
            CloseableHttpClient httpClient = getHttpClient(sapAccount, sapPassword);
            HttpPost httpPost = new HttpPost(url);
            String xmlnew = URLDecoder.decode(xml, "UTF-8");
            StringEntity entity = new StringEntity(xmlnew, ContentType.TEXT_XML);
            entity.setContentEncoding("UTF-8");
            entity.setContentType("text/xml");
            httpPost.setEntity(entity);

            CloseableHttpResponse result = httpClient.execute(httpPost);
            HttpEntity entityResponse = result.getEntity();
            response = EntityUtils.toString(entityResponse);
            log.info("调用SAP接口成功：URL:{},  REQUEST:{} ,RESPONSE:{} ", url, xml, response);
            httpClient.close();
        } catch (Exception e) {
            log.error("调用SAP接口失败：URL:{},  REQUEST:{} ,RESPONSE:{}", url, xml, response);
            e.printStackTrace();
        }
        return response;
    }

    public static String doHttpMethodSap(String urlxml, String xml, String sapAccount, String sapPassword) {
        System.out.println("url:" + urlxml);
        StringBuilder strBuf = new StringBuilder();
        try {
            URL urlNew = new URL(urlxml);
            HttpURLConnection conn = (HttpURLConnection) urlNew.openConnection();
            conn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            String auth = sapAccount + ":" + sapPassword;
            byte[] rel = Base64.encodeBase64(auth.getBytes());
            String res = new String(rel);
            conn.setRequestProperty("Authorization", "Basic " + res);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            log.info(xml);
            dos.write(xml.getBytes(StandardCharsets.UTF_8));
            dos.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line);
            }
            dos.close();
            reader.close();
            String result = strBuf.toString();
            log.info(result);
        } catch (Exception e) {
            log.error("调用SAP接口出错！" + e.getMessage());
            e.printStackTrace();
        }
        return strBuf.toString();
    }

}
